<template>
  <div class="cmt-container">
    <h3>发表评论</h3>
    <hr />
    <textarea placeholder="请输入要BB的内容（做多吐槽120字）" maxlength="120" v-model="msg"></textarea>
    <mt-button type="primary" size="large" @click="postMsg()">发表评论</mt-button>
    <div class="cmt-list">
      <div class="cmt-item" v-for="(item,i) in comments" :key="i">
        <div
          class="cmt-title"
        >第{{ i+1 }}楼&nbsp;&nbsp;用户：{{ item.user_name }}&nbsp;&nbsp;发表时间：{{ item.add_time | dateFormat }}</div>
        <div class="cmt-body">{{item.content}}</div>
      </div>
    </div>
    <mt-button type="danger" size="large" @click="getmore">加载更多</mt-button>
  </div>
</template>
<script>
import { Toast } from 'mint-ui';
export default {
  name: "",
  data() {
    return {
      // 默认页码为1
      pageindex: 1, //评论的页码
      comments: [], //存储已经发表的评论
      msg: "" //即将发表的评论内容
    };
  },
  components: {},
  created() {
    this.getComments();
  },
  mounted() {},
  methods: {
    async getComments() {
      const { data } = await this.$http.get(
        "api/getcomments/" + this.newsid + "?pageindex=" + this.pageindex
      );
      if (data.status === 0) {
        // 这里使用concat的目的是把下一页的内容拼接到原来的内容中，不应该直接把新页内容覆盖掉原来内容
        // console.log('data.message.length :>> ', data.message.length);
        if (data.message.length > 0) {
          this.comments = this.comments.concat(data.message);
        } else {
          Toast("没有更多数据了!");
        }
      } else {
        Toast("获取评论失败!");
      }
    },
    // 加载更多
    getmore() {
      this.pageindex++;
      this.getComments();
    },
    // 提交评论
    async postMsg() {
      if (this.msg.trim().length == 0) {
        Toast("请填写评论内容!");
      } else {
        //将数据提交到后端 
        const { data } = await this.$http.post(
          "/api/postcomment/" + this.newsid,
          { content: this.msg.trim() }
        );
        // 刷新当前页面的评论列表
        if (data.status === 0) {
          Toast(data.message);
          this.comments.unshift({
            user_name:'匿名用户',
            add_time:new Date(),
            content:this.msg.trim()
          });
          this.msg=''
        }
      }
    }
  },
  //   接收父组件传递过来的参数
  props: ["newsid"]
};
</script>
<style lang='scss' scoped>
.cmt-container {
  h3 {
    font-size: 18px;
  }
  textarea {
    font-size: 14px;
    height: 85px;
    margin: 0;
  }

  .cmt-list {
    margin: 5px 0;
    .cmt-item {
      font-size: 13px;
      .cmt-title {
        line-height: 30px;
        background-color: #ccc;
      }
      .cmt-body {
        line-height: 35px;
        text-indent: 2em;
      }
    }
  }
}
</style>
